package net.javamine.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.log4j.Logger;

/**
 * 拼音工具类
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-5-24
 * 1.create
 */
public class PinyinUtils {
	
	private static Logger log = Logger.getLogger(PinyinUtils.class);
	
	/**
	 * 汉字转拼音
	 * 
	 * @param input 汉字
	 * @return 汉语拼音
	 */
	public static String toPinyin(String input) {
		HanyuPinyinOutputFormat PINYIN_FORMAT = new HanyuPinyinOutputFormat();
		PINYIN_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		PINYIN_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c <= 255) {
				sb.append(c);
			} else {
				String pinyin = null;
				try {
					String[] pinyinArray = PinyinHelper
							.toHanyuPinyinStringArray(c, PINYIN_FORMAT);
					pinyin = pinyinArray[0];
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					ExceptionUtils.getExceptionMessage(log, e);
				} catch (NullPointerException e) {
					// 如果是日文，可能抛出该异常
					ExceptionUtils.getExceptionMessage(log, e);
				}
				if (pinyin != null) {
					sb.append(pinyin);
				}
			}
		}
		return sb.toString();
	}

}
